package com.lb.objectmapper;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhangjun
 * @Date: 2020/5/22 13:39
 * @Description:
 */

public class ObjectMapperTest {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Person person = new Person(1,"jack", "123456");
        Person person1 = new Person(2,"tom", "123456");

        System.out.println("===============对象转json=============");
        String personString = mapper.writeValueAsString(person);
        System.out.println(personString);

        System.out.println("==============json转对象==============");
        Person personFromString = mapper.readValue(personString,Person.class);
        System.out.println(personFromString);

        System.out.println("==============java集合转字符串==============");
        List<Person> personList = new ArrayList<>();
        personList.add(person);
        personList.add(person1);
        String jsonString = mapper.writeValueAsString(personList);
        System.out.println("JsonString List: " + jsonString);

        System.out.println("==============字符串转Java集合==============");
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Person.class);
        List<Person> persons = mapper.readValue(jsonString, javaType);
        persons.forEach(System.out::println);

        System.out.println("==============JsonNode==============");
        String message="{\"code\":\"EXCEPTION\",\"msgInfo\":\"交易支付异常\"} ";
        JsonNode jsonNode = mapper.readTree(message);
        String code = jsonNode.get("code").asText();
        System.out.println("code:" + code);

        List<Long> list = Lists.newArrayList();
        System.out.println(mapper.writeValueAsString(list));
    }
}
